<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        <el-button
          class="icon-button back-button"
          style="margin-right: 10px"
          @click="$router.back()"
        >
          <i class="el-icon-arrow-left" style="font-size: 12px"></i>
        </el-button>
        <span style="display:flex">
          <link-button
            v-if="authrole === 'system_admin'"
            :disabled="authrole !== 'system_admin'"
            :content="poolData.resource_pool_name"
            @click="
              $router.push({
                name: 'PoolDetail',
                query: { poolid: poolData.resource_pool_id },
              })
            "
          />
         {{ authrole !== 'system_admin' ? poolData.resource_pool_name : '' }}&nbsp;/&nbsp;{{ poolData.resource_name }}&nbsp;/&nbsp;{{ poolData.name }}
        </span>
        <i v-if="false" class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card>
          <basic-table
            v-loading="loading"
            tableType="HorizonDaas"
            ref="Daas"
            :pageMethod="
              (params) => {
              if(selectSearchType == 'order_id') {
                params.order_id = searchValue
              } else {
                delete params.order_id
              }
              if(selectSearchType == 'instance_id') {
                params.instance_id = searchValue
              } else {
                delete params.instance_id
              }
              if(selectSearchType == 'workarea_name') {
                params.workarea_name = searchValue
              } else {
                delete params.workarea_name
              }
              if(selectSearchType == 'desktop_name') {
                params.name = searchValue
              } else {
                delete params.name
              }
                params.resource_class = 'HorizonDaas';
                return $pandaApi.getDesktops(poolData.id, params);
              }
            "
          >
            <template #table-options="tableSlotData">
              <div class="table-left-options">
                <!-- 重启 -->
                <el-button
                  class="icon-button setting-button"
                  :disabled="tableSlotData.table.selectRows.length === 0"
                  style="width: auto;"
                  @click="operation(tableSlotData.table.selectRows, 'RESET',true)"
                >
                  <i
                    class="iconfont iconzhongyiicon_guanji-zhongqi"
                    style="font-size: 12px; margin-right: 5px"
                  ></i>
                  <span style="font-size: 12px">{{
                    $t("desktopManage.operation.reset")
                  }}</span>
                </el-button>
                <!-- 开机 -->
                <el-button
                  class="icon-button setting-button"
                  :disabled="tableSlotData.table.selectRows.length === 0"
                  style="width: auto; margin-right: 10px"
                  @click="operation(tableSlotData.table.selectRows, 'POWERON',true)"
                >
                  <i
                    class="iconfont iconzhongyiicon_kaiji"
                    style="font-size: 12px; margin-right: 5px"
                  ></i>
                  <span style="font-size: 12px">{{
                    $t("desktopManage.operation.boot")
                  }}</span>
                </el-button>
                <el-dropdown>
                  <el-button
                    class="icon-button setting-button"
                    :disabled="tableSlotData.table.selectRows.length === 0"
                    style="width: auto; font-size: 12px"
                  >
                    {{ $t("common.More")
                    }}<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <!-- 关机 -->
                  <el-dropdown-menu slot="dropdown">
                    <!-- <el-dropdown-item
                      @click.native="
                        operation(tableSlotData.table.selectRows, 'SHUTDOWN')
                      "
                      >{{
                        $t("desktopManage.operation.shutdown")
                      }}</el-dropdown-item
                    > -->
                    <!-- 强制关机 --关机 -->
                    <el-dropdown-item
                      @click.native="
                        operation(tableSlotData.table.selectRows, 'POWEROFF',true)
                      "
                      >{{
                        $t("desktopManage.operation.powerOff")
                      }}</el-dropdown-item
                    >
                    <!-- 强制重启 -->
                    <!-- <el-dropdown-item
                      @click.native="
                        operation(tableSlotData.table.selectRows, 'RESET')
                      "
                      >{{
                        $t("desktopManage.operation.reset")
                      }}</el-dropdown-item
                    > -->
                    <!-- 注销 -->
                    <!-- <el-dropdown-item
                      @click.native="
                        operation(tableSlotData.table.selectRows, 'SUSPEND')
                      "
                      >{{
                        $t("desktopManage.operation.logout")
                      }}</el-dropdown-item
                    > -->
                    <!-- 断开 -->
                    <el-dropdown-item
                      @click.native="
                        operation(tableSlotData.table.selectRows, 'DISCONNECT',true)
                      "
                      >{{
                        $t("desktopManage.operation.disconnect")
                      }}</el-dropdown-item
                    >
                    <!-- 外设策略 -->
                    <el-dropdown-item
                      @click.native="policy(tableSlotData.table.selectRows,true)"
                      >{{
                        $t("desktopManage.operation.policy")
                      }}</el-dropdown-item
                    >
                    <!-- 发送通知 -->
                    <el-dropdown-item
                      @click.native="
                        sendMessage(tableSlotData.table.selectRows,true)
                      "
                      >{{
                        $t("desktopManage.operation.sendNotification")
                      }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="table-right-options">
                <!-- <el-input
                  :placeholder="$t('desktopManage.message.searchDesktops')"
                  v-model="searchValue"
                  style="width: 200px;"
                  @keyup.enter.native="tableSearchChange(tableSlotData)"
                >
                </el-input> -->
                <el-select v-model="selectSearchType" style="width:200px">
                  <el-option label="订单号" value="order_id"></el-option>
                  <el-option label="资源实例ID" value="instance_id"></el-option>
                  <el-option label="工作区名称" value="workarea_name"></el-option>
                  <el-option label="桌面名称" value="desktop_name"></el-option>
              </el-select>
              <el-input
                  :placeholder="$t(`workspace.selectSearchType.${selectSearchType}`)" 
                  v-model="searchValue" 
                  @keyup.enter.native="tableSearchChange(tableSlotData)"
                  class="input-with-select"
                >
                </el-input>
                <el-button @click="tableSearchChange(tableSlotData)" type="primary" style="margin-left: 10px;" >{{ $t('common.search') }}</el-button>
              </div>
            </template>
            <template #table-column="tableSlotData">
              <el-table-column
                type="selection"
                width="40"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="workarea_name"
                :label="$t('workspace.workSpace')"
              >
	      	<template #default="props">
                  <span>{{ props.row.workarea_name || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                width="250"
                :label="$t('desktopManage.desktopName')"
              >
                <template #default="props">
                  <div style="display:flex">
                    {{ props.row.name }}
                    <el-tooltip class="item" effect="dark" v-if="props.row.pretty_name" :content="props.row.pretty_name" placement="right">
                      <el-tag type="success" style="margin-left:5px;width:100px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{ (props.row.pretty_name) }}</el-tag>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="cpu"
                :label="$t('desktopManage.standard')"
              >
              <template #default="props">
                {{getCpus(props.row.cpus, props.row.memory_mb)}}
              </template>
              </el-table-column>
              <el-table-column
                prop="ip_addr"
                :label="$t('desktopManage.IPAddress')"
              >
              </el-table-column>
              <el-table-column
                prop="order_id"
                :label="$t('order.orderNumber')"
              >
                <template #default="props">
                  <span>{{ props.row.order_id || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="instance_id"
                :label="$t('workspace.resourceInstanceID')"
              >
                <template #default="props">
                  <span>{{ props.row.instance_id || "-" }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-if="authrole != 'tenant_admin'"
                prop="cloud_tenant_name"
                :label="$t('desktopManage.belongsToTheTenant')"
              >
              </el-table-column>
              <el-table-column
                prop="username"
                :label="$t('desktopManage.assigningUsers')"
              >
              <template #default="props">
                {{getUserName(props.row)}}
              </template>
              </el-table-column>
              <el-table-column
                prop="power_state"
                :label="$t('desktopManage.powerStatus')"
                :formatter="
                  (row, column) => {
                    if (row.power_state) {
                      return $t(`desktopManage.powerState.${row.power_state}`);
                    }
                    return '';
                  }
                "
              >
              </el-table-column>
              <el-table-column
                prop="state"
                :label="$t('desktopManage.taskStatus')"
                :formatter="
                  (row, column) => {
                    if (row.state) {
                      return $t(`desktopManage.state.${row.state}`);
                    }
                    return '';
                  }
                "
              >
              </el-table-column>
              <el-table-column
                prop="daas_agent_state"
                :label="$t('desktopManage.AgentStatus')"
                :formatter="
                  (row, column) => {
                    if (row.daas_agent_state) {
                      return $t(
                        `desktopManage.agentState.${row.daas_agent_state}`
                      );
                    }
                    return '';
                  }
                "
              >
              </el-table-column>
              <el-table-column
                prop="vmware_tools_state"
                :label="$t('desktopManage.VMToolStatus')"
                :formatter="
                  (row, column) => {
                    if (row.vmware_tools_state) {
                      return $t(
                        `desktopManage.VMToolState.${row.vmware_tools_state}`
                      );
                    }
                    return '';
                  }
                "
              >
              </el-table-column>
              <el-table-column :label="$t('common.action')" width="200">
                <template #default="props">
                  <!-- 分配 -->
                  <link-button
                    v-if="authrole !== 'system_admin'"
                    :content="$t('desktopManage.operation.distribution')"
                    :size="10"
                    :font-size="'12px'"
                    style="margin-right: 15px"
                    @click="distribution(props.row)"
                  />
                  <!-- 开机 -->
                  <link-button
                    :content="$t('desktopManage.operation.boot')"
                    :disabled="(props.row.power_state === 'POWERED_ON') || props.row.in_maintenance_mode === true"
                    :size="10"
                    :font-size="'12px'"
                    style="margin-right: 15px"
                    @click="operation(props.row, 'POWERON')"
                  />
                  <!-- 关机 -->
                  <link-button
                    v-if="authrole === 'system_admin'"
                    :disabled="(props.row.power_state === 'POWERED_OFF') || props.row.in_maintenance_mode === true"
                    :content="$t('desktopManage.operation.powerOff')"
                    :size="10"
                    :font-size="'12px'"
                    style="margin-right: 15px"
                    @click="operation(props.row, 'POWEROFF')"
                  />
                  <el-dropdown>
                    <el-button type="text" class="el-dropdown-link">
                      {{ $t("common.More")
                      }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <!-- 关机 -->
                      <!-- <el-dropdown-item
                        @click.native="operation(props.row, 'SHUTDOWN')"
                        :disabled="props.row.power_state === 'POWERED_OFF'"
                        >{{
                          $t("desktopManage.operation.shutdown")
                        }}</el-dropdown-item
                      > -->
                      <!-- 强制关机 -- 关机 -->
                      <el-dropdown-item
                        v-if="authrole !== 'system_admin'"
                        :disabled="(props.row.power_state === 'POWERED_OFF') || props.row.in_maintenance_mode === true"
                        @click.native="operation(props.row, 'POWEROFF')"
                        >{{
                          $t("desktopManage.operation.powerOff")
                        }}</el-dropdown-item
                      >
                      <!-- 重启 -->
                      <el-dropdown-item
                        :disabled="(props.row.power_state === 'POWERED_OFF') || props.row.in_maintenance_mode === true"
                        @click.native="operation(props.row, 'RESET')"
                        >{{
                          $t("desktopManage.operation.reset")
                        }}</el-dropdown-item
                      >
                      <!-- 注销 -->
                      <!-- <el-dropdown-item
                        :disabled="props.row.power_state === 'POWERED_OFF'"
                        @click.native="operation(props.row, 'SUSPEND')"
                        >{{
                          $t("desktopManage.operation.logout")
                        }}</el-dropdown-item
                      > -->
                      <!-- 断开 -->
                      <el-dropdown-item
                        :disabled="(props.row.power_state === 'POWERED_OFF' || props.row.is_connected == false) || props.row.in_maintenance_mode === true"
                        @click.native="operation(props.row, 'DISCONNECT')"
                        >{{
                          $t("desktopManage.operation.disconnect")
                        }}</el-dropdown-item
                      >
                      <!-- 取消分配用户 -->
                      <el-dropdown-item
                        v-if="authrole !== 'system_admin'"
                        :disabled="!getUserName(props.row) ? true : false"
                        @click.native="operation(props.row, 'UnassignUser')"
                        >{{
                          $t("desktopManage.operation.unassignUser")
                        }}</el-dropdown-item
                      >
                      <!-- 外设策略 -->
                      <el-dropdown-item
                        @click.native="policy(props.row)" 
                        :disabled="(props.row.cloud_tenant_id ? false : true) || props.row.in_maintenance_mode === true">{{
                        $t("desktopManage.operation.policy")
                      }}</el-dropdown-item>
                      <!-- 发送通知 -->
                      <el-dropdown-item
                        :disabled="props.row.power_state === 'POWERED_OFF' || props.row.in_maintenance_mode === true"
                        @click.native="sendMessage(props.row)"
                        >{{
                          $t("desktopManage.operation.sendNotification")
                        }}</el-dropdown-item
                      >
                      <!-- 设置别名 -->
                      <el-dropdown-item
                        @click.native="setPrettyName(props.row)"
                        >
                        {{
                          $t("desktopManage.operation.setPrettyName")
                        }}
                      </el-dropdown-item>
                      <!-- 绑定终端 -->
                      <el-dropdown-item
                        @click.native="bindClient(props.row)"
                        >
                        {{ $t('desktopManage.operation.bindClient') }}
                      </el-dropdown-item>
                      <!-- 取消绑定终端 -->
                      <el-dropdown-item
                        :disabled="props.row.bind_clients.length <= 0"
                        @click.native="cancelBindClient(props.row)"
                        >
                        {{ $t('desktopManage.operation.cancelBindClient') }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
            <template #others-elements="tableSlotData">
              <desktop-pool-operation-form-dialog
                @success="refreshDesktopPool"
                ref="operation"
              />
              <desktop-pool-select-form-dialog
                @success="refreshDesktopPool"
                ref="distribution"
              />
              <desktop-pool-policy-form-dialog
                @success="refreshDesktopPool"
                ref="policy"
              />
              <desktop-pool-send-message-form-dialog
                @success="refreshDesktopPool"
                ref="send"
              />
              <!-- 设置别名 -->
              <desktop-set-pretty-name-form-dialog @success="refreshDesktopPool" ref="setPrettyName"></desktop-set-pretty-name-form-dialog>
              <!-- 绑定终端 -->
              <desktop-bind-client ref="DesktopBindClient" @success="refreshDesktopPool"></desktop-bind-client>
              <!-- 取消绑定终端 -->
              <desktop-cancel-bind-clients-form-dialog ref="DesktopCancelBindClientsFormDialog" @success="refreshDesktopPool"></desktop-cancel-bind-clients-form-dialog>
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import BasicTable from "../../../../components/Basic/Table/BasicTable.vue";
import LinkButton from "../../../../components/Basic/Button/LinkButton.vue";
import DesktopPoolOperationFormDialog from "./../../components/desktopPoolOperationFormDialog.vue";
import DesktopPoolSelectFormDialog from "./../../components/desktopPoolSelectFormDialog.vue";
import DesktopPoolPolicyFormDialog from "./../../components/desktopPoolPolicyFormDialog.vue";
import DesktopPoolSendMessageFormDialog from "./../../components/desktopPoolSendMessageFormDialog.vue";
import { AuthModule } from "../../../../store/modules/auth";
import { getCpus } from "../../../../utils/auth";
import { get } from "sortablejs";
import DesktopSetPrettyNameFormDialog from './../../components/desktopSetPrettyNameFormDialog.vue';
import DesktopBindClient from '../../components/desktopBindClientFormDialog.vue';
import DesktopCancelBindClientsFormDialog from '../../components/desktopCancelBindClientsFormDialog.vue';
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
    DesktopPoolOperationFormDialog,
    DesktopPoolSelectFormDialog,
    DesktopPoolPolicyFormDialog,
    DesktopPoolSendMessageFormDialog,
    DesktopSetPrettyNameFormDialog,
    DesktopBindClient,
    DesktopCancelBindClientsFormDialog
  },
  data() {
    return {
      loading: false,
      poolData: {},
      searchValue: "",
      userList: [],
      authrole: AuthModule.authrole,
      tableSearch: false,
      selectSearchType: 'order_id',
    };
  },
  computed: {
    getCpus: () => getCpus
  },
  async created() {
    this.poolData = {
      id: (this as any).$route.query.poolid,
    };
    await (this as any).getDetailData();
  },
  methods: {
    cancelBindClient(row: any) {
      (this as any).$refs['DesktopCancelBindClientsFormDialog'].init(row)
    },
    bindClient(row: any) {
      (this as any).$refs['DesktopBindClient'].init(row);
    },
    setPrettyName(row: any) {
      (this as any).$refs['setPrettyName'].init(row);
    },
    getUserName(row: any) {
      if (row.occupied_user.database.account_name) {
        return row.occupied_user.database.account_name;
      } else if (row.occupied_user.vmware.occupied_username) {
        return row.occupied_user.vmware.occupied_username
      } else if (row.occupied_user.database.auth_id) {
        return row.occupied_user.database.auth_id
      } else {
        return '';
      }
    },
    // 页面刷新重置page
    tableSearchChange(table: any) {
      (this as any).tableSearch = true;
      table.table.refresh(true);
    },
    async getDetailData() {
      (this as any).$pandaApi
        .getDesktopPools({ id: (this as any).poolData.id })
        .then((res: any) => {
          this.poolData = res[0];
        });
    },
    refreshDesktopPool() {
      (this.$refs["Daas"] as any).refresh();
    },

    operation(data: any, type: string,isBatch: any) {
      if(isBatch) {
        for(let i in data) {
          if(data[i].in_maintenance_mode === true) {
            this.$message.warning(this.$t('message.frozenTip').toString());
            return;
          }
        }
      }
      let obj: any = {};
      obj.type = type;
      obj.data = data;
      (this.$refs["operation"] as any).init(obj);
    },
    distribution(data: any) {
      let obj: any = {};
      let options: any = [];
      obj.type = "HorizonDaas";
      obj.data = data;
      (this.$refs["distribution"] as any).init(obj);
    },
    policy(data: any,isBatch: any) {
      if(isBatch) {
        for(let i in data) {
          if(data[i].in_maintenance_mode === true) {
            this.$message.warning(this.$t('message.frozenTip').toString());
            return;
          }
        }
      }
      if (Array.isArray(data)) {
        let isDifferent = false;
        for (let i = 0; i <= data.length -2; i ++) {
          if (data[i].cloud_tenant_id !== data[i+1].cloud_tenant_id) {
            isDifferent = true;
          }
        }
        if (isDifferent) {
          this.$message.warning((this as any).$t('message.policyErr'));
        } else {
          this.loading = true;
          let obj: any = {};
          obj.data = data;
          obj.options = [];
          (this as any).$pandaApi
            .apiGetUsbRuleGroupsByPage({cloud_tenant_id: data[0].cloud_tenant_id})
            .then((res: any) => {
              this.loading = false;
              res.forEach((item: any) => {
                if (item.name === "Default USB Rule Group") {
                  item.name = this.$t("policy.DefaultUSBRuleGroup");
                }
                obj.options.push(item);
              });
              (this.$refs["policy"] as any).init(obj);
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                message: (this as any).$t('desktopManage.message.getPolicyData'),
                type: "warning",
              });
            });
        }
      } else {
        this.loading = true;
        let obj: any = {};
        obj.data = data;
        obj.options = [];
        (this as any).$pandaApi
          .apiGetUsbRuleGroupsByPage({cloud_tenant_id: data.cloud_tenant_id})
          .then((res: any) => {
            this.loading = false;
            res.forEach((item: any) => {
              if (item.name === "Default USB Rule Group") {
                item.name = this.$t("policy.DefaultUSBRuleGroup");
              }
              obj.options.push(item);
            });
            (this.$refs["policy"] as any).init(obj);
          })
          .catch(() => {
            this.loading = false;
            this.$message({
              message: (this as any).$t('desktopManage.message.getPolicyData'),
              type: "warning",
            });
          });
      }
    },
    sendMessage(data: any,isBatch: any) {
      if(isBatch) {
        for(let i in data) {
          if(data[i].in_maintenance_mode === true) {
            this.$message.warning(this.$t('message.frozenTip').toString());
            return;
          }
        }
      }
      let obj: any = {};
      obj.data = data;
      (this.$refs["send"] as any).init(obj, false);
    }
  },
});
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #eff1f4;

  .page-header {
    height: 60px;
    background-color: #ffffff;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #d9d9d9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;
      display: flex;
      align-items: center;

      .back-button {
        width: 24px;
        height: 24px;
        padding: 0px 6px;
      }

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;

      .content-info {
        margin-bottom: 20px;

        ::v-deep .el-form-item {
          margin-bottom: 0px;
          margin-right: 40px;
        }

        ::v-deep .el-form-item__label,
        ::v-deep .el-form-item__content {
          color: #999999;
          font-size: 12px;
        }

        ::v-deep .el-form-item__content {
          color: #333333;
        }
      }
    }
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}
</style>
